﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Navigation;
using System.Linq;
using System.Resources;
using System.Threading;
using System.Globalization;
using System.Reflection;
using Motesrummet.Web.Helpers;
using Microsoft.SharePoint.WebControls;

namespace Motesrummet.Web.AddRemoveDepartmentWebPart
{

    public partial class AddRemoveDepartmentWebPartUserControl : UserControl
    {
        private string SiteURL;
        private string SiteTitle;
        private string SiteDescription;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                PopulateDropdowns();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {

            ScriptLink.Register( this.Page, "/_layouts/Motesrummet.Web/Scripts/valid.js", false);
            base.OnPreRender(e);
        }
  

        protected void btn_CreateSite_Click(object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Site.RootWeb;

            try
            {
                web.AllowUnsafeUpdates = true;
                SetGUIValues();
                SPWebTemplate template = SetTemplateNewSite(web);

                using (SPWeb myWeb = SPContext.Current.Site.OpenWeb(SiteURL))
                {
                    if (!String.IsNullOrEmpty(SiteURL) && !String.IsNullOrEmpty(SiteTitle) && !myWeb.Exists)
                    {
                        ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)Page.Master.FindControl("PlaceHolderPageTitle");
                        contentPlaceHolder.Controls.Clear();
                        LiteralControl literalControl = new LiteralControl();
                        literalControl.Text = SiteTitle;
                        contentPlaceHolder.Controls.Add(literalControl); 

                        SPWeb newWeb = web.Site.AllWebs.Add(SiteURL, SiteTitle, SiteDescription, 1033, template, true, false);
                        SetNewSiteTemplate(myWeb, newWeb);
                        ResetGUIValues();
                        AddWebToDeleteSitesDropdown(newWeb.Title, newWeb.ID);
                        createNavigation(SiteTitle, SiteURL);
                        lbl_CreateSite.Text = String.Format(ResourceHelper.getString("str_success"), SiteTitle, myWeb.Url, myWeb.Url);
                    }
                    else if (String.IsNullOrEmpty(SiteURL) || String.IsNullOrEmpty(SiteTitle))
                    {
                        lbl_CreateSite.Text = ResourceHelper.getString("str_must_have");
                    }
                    else
                    {
                        lbl_CreateSite.Text = String.Format(ResourceHelper.getString("str_already_exist"), SiteTitle);
                    }
                }
            }

            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }



        protected void btn_DeleteSite_Click(object sender, EventArgs e)
        {
            SPSite site = SPContext.Current.Site;

            using (SPWeb web = site.OpenWeb())
            {
                SPWebCollection webColl = web.GetSubwebsForCurrentUser();
                string selVal = drpd_WebSites.SelectedValue;
                var result = (from w in webColl
                              where w.Title.Equals(selVal)
                              select w).FirstOrDefault();

                try
                {
                    //lbl_DeleteSite.Text = String.Format(Resources.Resources_SE.str_delete, result.Title);
                    //Ta bort från dropdown

                    drpd_WebSites.Items.Remove(result.Title);
                    //ta bort sidan (från collection)
                    lbl_DeleteSite.Text = String.Format(ResourceHelper.getString("str_delete"), result.Title);

                    result.Delete();
                }
                catch (Exception)
                {
                    lbl_DeleteSite.Text = "FEL";
                }
            }
        
        }


        //add v5 MasterPage Layout to new custom site (from web part)
        private static void SetNewSiteTemplate(SPWeb myWeb, SPWeb newWeb)
        {
            var root = myWeb.Site.RootWeb.Url;
            var siteMaster = new Uri(root +
                             "/_catalogs/masterpage/" +
                             "v5.Master");
            newWeb.CustomMasterUrl = siteMaster.AbsolutePath;

            var systemMaster = new Uri(root +
                               "/_catalogs/masterpage/" +
                               "v5.Master");
            newWeb.MasterUrl = systemMaster.AbsolutePath;

            newWeb.Update();
        }

        private void AddWebToDeleteSitesDropdown(string title, Guid guid)
        {
            drpd_WebSites.Items.Add(new ListItem(title, guid.ToString()));
        }

        private static SPWebTemplate SetTemplateNewSite(SPWeb web)
        {
            SPWebTemplate template = web.GetAvailableWebTemplates((uint)1033)
                                                                   .Cast<SPWebTemplate>()
                                                                   .Where(x => x.Title.Equals("Template_Motesrummet"))
                                                                   .First();
            return template;
        }

  

        private void ResetGUIValues()
        {
            txt_Url.Text = string.Empty;
            txt_Title.Text = string.Empty;
            txt_Description.Text = string.Empty;
        }

        private void SetGUIValues()
        {
            SiteURL = txt_Url.Text;
            SiteTitle = txt_Title.Text;
            SiteDescription = txt_Description.Text;
        }


        private void PopulateDropdowns()
        {
            SPSite site = SPContext.Current.Site;
            using (SPWeb web = site.OpenWeb())
            {
                SPWebCollection sub = web.GetSubwebsForCurrentUser();

                foreach (SPWeb subsites in sub)
                {
                    drpd_WebSites.Items.Add(subsites.Title);
                    subsites.Dispose();
                }
            }
        }

        private void createNavigation(string linkTitle, string linkUrl)
        {

            SPSite site = SPContext.Current.Site;
            {
                using (SPWeb webb = site.OpenWeb(linkUrl))
                {
                    if (!webb.IsRootWeb)
                        webb.Navigation.UseShared = true;

                    if (!webb.ParentWeb.Navigation.UseShared)
                    {
                        SPNavigationNodeCollection topnav = webb.ParentWeb.Navigation.TopNavigationBar;
                        SPNavigationNode node = topnav
                            .Cast<SPNavigationNode>()
                            .FirstOrDefault(n => n.Url.Equals(webb.ServerRelativeUrl));

                        if (node == null)
                        {
                            string LinkTitle = linkTitle;

                            if (LinkTitle.Length > 15)
                            {
                                LinkTitle = LinkTitle.Substring(0, 12) + "...";

                                node = new SPNavigationNode(LinkTitle, webb.ServerRelativeUrl);
                                node = topnav.AddAsLast(node);
                            }
                            else
                            {
                                node = new SPNavigationNode(LinkTitle, webb.ServerRelativeUrl);
                                node = topnav.AddAsLast(node);
                            }
                            node.Update();

                        }
                    }
                }
            }
        }

    }
}
